package io.ede.modules.ede.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.ede.common.utils.HttpClient;
import io.ede.common.utils.SysAttrConfigConstant;
import io.ede.modules.ede.entity.SysAttrConfigEntity;
import io.ede.modules.ede.service.SysAttrConfigService;
import io.ede.modules.sys.entity.SysUserEntity;
import io.ede.modules.sys.service.SysUserService;
import io.ede.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2019-09-12 16:13:57
 */
@RestController
@RequestMapping("ede/sdmarks")
public class SdMakersController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysAttrConfigService sysAttrConfigService;

    private String appid = "087b15a7d8ee11e98aa67cd30ad32d28";
    private String appkey = "sKIWDvGYAvhJGFd9H6RKJTuPinpaag2E";
    //回调地址
    private String redirectUri = "http://ede.qdmay.top/ede/sdmarks/receive_code";

    private String loingUrl = "http://oauth.sdmakers.cn/oauth/authorize";

    /**
     * 与创客平台交互
     * 验证用户登录状态
     *
     * @return
     */
    @RequestMapping("/login")
    public void login(HttpServletResponse httpServletResponse) {
        StringBuffer sbb = new StringBuffer().append("scope=read&response_type=code");
        //向创客认证平台发送请求
        try {
            sbb.append("&client_id=").append(appid);
            sbb.append("&redirect_uri=").append(redirectUri);
            HttpClient httpClient = new HttpClient();
            httpClient.sendGet(loingUrl, sbb.toString());
            httpServletResponse.sendRedirect(loingUrl + "?" + sbb);
        } catch (Exception e) {
        }
    }

    /**
     * 与创客平台交互
     * Code换取AccessToken
     */
    @RequestMapping("/receive_code")
    public void receiveCode(@RequestParam Map<String, Object> params, HttpServletResponse httpServletResponse) {
        try {
            //code换取AccessToken
            String code = params.get("code").toString();
            String url = "http://oauth.sdmakers.cn/oauth/token";
            StringBuffer sbb = new StringBuffer();
            sbb.append("client_id=").append(appid);
            sbb.append("&client_secret=").append(appkey);
            sbb.append("&grant_type=").append("authorization_code");
            sbb.append("&code=").append(code);
            sbb.append("&redirect_uri=").append(redirectUri);
            HttpClient httpClient = new HttpClient();
            String json = httpClient.sendGet(url, sbb.toString());
            JSONObject jsonObject = JSON.parseObject(json);
            String accessToken = jsonObject.getString("access_token");
            //使用AccessToken获取用户信息
            String userUrl = "http://oauth.sdmakers.cn/unity/client_user";
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("client_id=").append(appid);
            stringBuffer.append("&access_token=").append(accessToken);
            stringBuffer.append("&scope=").append("read");
            httpClient = new HttpClient();
            String jsonStr = httpClient.sendGet(userUrl, stringBuffer.toString());
            String decodeStr = URLDecoder.decode(jsonStr, "UTF-8");
            JSONObject jsonObjectStr = JSON.parseObject(decodeStr);
            String openId = jsonObjectStr.getString("openid");
            if (StringUtils.isBlank(openId)) {
                httpServletResponse.sendRedirect("http://org.sdmakers.cn/admin.html#/");
            } else {
                String name = jsonObjectStr.getString("name");
                Map<String, Object> param = new HashMap<>();
                param.put("open_id", openId);
                List<SysUserEntity> sysUserEntityList = (List<SysUserEntity>) sysUserService.listByMap(param);
                if (sysUserEntityList.size() == 0) {
                    sysUserService.saveUserAndRole(openId, name);
                }
                Subject subject = ShiroUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(name, "123456");
                subject.login(token);
                //加载系统配置
                List<SysAttrConfigEntity> list = sysAttrConfigService.list();
                if(list!=null&&list.size()>0){
                    SysAttrConfigConstant.sysAttrConfigEntity = sysAttrConfigService.list().get(0);
                }
                httpServletResponse.sendRedirect("/index.html");
            }
        } catch (Exception e) {
        }
    }


}
